
class Tabber < Pan::Component
  attr_accessor :active, :tabs
  def initialize(title=nil)
    @title = title
    @tabs = []
    @active = 0
    yield(self) if block_given?
  end

  def add_tab(title, content)
    tabs << [title, content]
  end

  alias add add_tab

  def active_tabname
    tabs[active][0]
  end

  def active_content
    tabs[active][1]
  end

  def activate_by_name(name)
    pos = tabs.pos {|ea| ea[0] == name}
    self.activate_by_index(pos) if pos
  end

  def activate_by_index(i)
    self.active = i
  end

  def render_on(html)
    if Dynamic.current_req.path.match /\/app\/([A-Za-z]+)/
      puts "TABBER match #{$1}"
      activate_by_name($1.gsub("_"," "))
    end

    if @title
      html.div("id"=>"page-head") {
        html.div("id"=>"page-head-title") {
          html.heading(@title)
        }
      }
    end
    html.div("id"=>"navigation") {
      html.ul("id"=>"tabnav") {
        @tabs.each_with_index do |each, index|
          title, content = each
          if index == active
            html.li("class"=>"active tab") { html.link(title) { self.activate_by_index(index) } }
          else
            html.li("class"=>"tab") { html.link(title) { self.activate_by_index(index) } }
          end
        end
      }
    }
    html.render(active_content())
  end

  def callbacks_done(chain)
    Dynamic.current_req.add_to_path "#{active_tabname.gsub(" ","_")}"
    active_content.callbacks_done(chain << self)
  end

end
